<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Http\Lib;


use Selibra\Di\Container\ContainerCollector;
use Selibra\Di\DI;
use Selibra\Http\Interceptor\RequestInterceptor;
use Selibra\Http\Interceptor\RequestSpaceInterceptorCollector;
use Selibra\Http\Interceptor\RequestSpaceNode;
use Selibra\Http\Protocol\InterceptorInterface;
use Selibra\Http\Protocol\RequestInterceptorInterface;
use Selibra\Http\Session;
use Selibra\Tools\Console;

class Interceptor implements InterceptorInterface
{

    /**
     * @var string
     */
    protected string $pathInfo;


    /**
     * @param Session $session
     * @throws \ReflectionException
     * @throws \Selibra\Di\Exception\NoImplementClass
     */
    public function before(Session $session)
    {
        /** @var RequestSpaceNode[] $interceptors */
        $interceptors = RequestSpaceInterceptorCollector::getInterceptors(
            $this->getPathInfo(),
            strtoupper($session->getRequest()->getMethod())
        );
        $interceptorsAny = RequestSpaceInterceptorCollector::getInterceptors(
            $this->getPathInfo(),
            "ANY"
        );
        $interceptors += $interceptorsAny;

        foreach ($interceptors as $interceptor) {
            $namespace = $interceptor->getNamespace();
            $method = $interceptor->getMethod();
            $interceptorInt = DI::getObjectContext($namespace);
            if (!empty($interceptorInt)) {
                $interceptorInt->$method($session);
            }
        }
    }


    public function after($data)
    {
    }

    /**
     * @return string
     */
    public function getPathInfo(): string
    {
        return $this->pathInfo;
    }

    /**
     * @param string $pathInfo
     * @return $this
     */
    public function setPathInfo(string $pathInfo)
    {
        $this->pathInfo = $pathInfo;
        return $this;
    }

}